import { Injectable } from '@angular/core';
import { AppConfig } from "../config";
import { Http, Headers, RequestOptions } from "@angular/http";
import { Observable } from "rxjs/Observable";
import { DatePipe } from "@angular/common";
import { ActualWindPower } from "../entity/actual-wind-power.model";
import { PowerLoss } from "../entity/power-loss.model";
import { WindPowers } from "../entity/wind-powers.model";
import { InterceptorService } from '../service/interceptor/interceptor-service';

@Injectable()
export class ActualWindPowerService {

  private fomat: string = "yyyy-MM-dd";
  private readonly baseUrl = `${AppConfig.APP_RESTFUL}`;

  // 功率曲线
  private readonly param = "actualWindPowers/getActualWindPowerVOByIds";
  private readonly paramDate = "actualWindPowers/getTurbineActualVOByDates";
  private readonly url = `${this.baseUrl}/${this.param}`;
  private readonly urlDate = `${this.baseUrl}/${this.paramDate}`;

  // 风场能力评估(年度)
  private readonly paramFarmYear = "powerLosses/getCurvePowGenAssVOListByFarm";
  private readonly paramTurbineYear = "powerLosses/getCurvePowGenAssVOListByTurbines";
  private readonly urlFarmYear = `${this.baseUrl}/${this.paramFarmYear}`;
  private readonly urlTurbineYear = `${this.baseUrl}/${this.paramTurbineYear}`;

  // 风场能力评估(月度)
  private readonly paramFarmMonth = "powerLosses/getCurvePowGenAssVOListByFarmDay";
  private readonly paramTurbineMonth = "powerLosses/getCurvePowGenAssVOListByTurbinesDay";
  private readonly urlFarmMonth = `${this.baseUrl}/${this.paramFarmMonth}`;
  private readonly urlTurbineMonth = `${this.baseUrl}/${this.paramTurbineMonth}`;

  // 风机能力评估(年度)
  private readonly paramTurbineIdYear = "powerLosses/getCurvePowGenAssVOListByOneYear";
  private readonly urlTurbineIdYear = `${this.baseUrl}/${this.paramTurbineIdYear}`;

  private readonly paramTurbineIdMonth = "powerLosses/getCurvePowGenAssVOListByOneMonth";
  private readonly urlTurbineIdMonth = `${this.baseUrl}/${this.paramTurbineIdMonth}`;

  constructor(
    private http: InterceptorService,
    private datePipe: DatePipe) { }

  /**
  * 获取同一型号多个风机功率集合
  * 
  * @returns {Promise<ActualWindPower[]>} 
  * @memberof ActualWindPowerService
  */
  getWindPowerData(deviceIds: number[], dateType: number, date: Date): Promise<{ actualWindPowerList: ActualWindPower[]; powerLossList: PowerLoss[]; windPowerList: WindPowers[]; }> {

    let dateFomat: string = "";
    if (deviceIds == null)
      return Promise.reject("请选择风机！");
    if (dateType.toString() == '') return;
    dateFomat = this.datePipe.transform(date, this.fomat);
    return this.http.post(this.url, JSON.stringify({ 'deviceIds': deviceIds, 'dateType': dateType, 'date': dateFomat }))
      .toPromise()
      .then(response => {
        let resault = response.json();
        try {
          switch (resault.code) {
            case "200":
              return resault.data;
            case "-1":
              throw new Error(resault.message);
          }
        }
        catch (error) {
          throw error;
        }
      })
      .catch(this.handleError);
  }

  /**
  * 获取单个风机功率集合
  * 
  * @returns {Promise<ActualWindPower[]>} 
  * @memberof ActualWindPowerService
  */
  getWindPowerDataByTurbId(deviceIds: number[], dateType: number, startTime: Date, endTime: Date): Promise<{ actualWindPowerList: ActualWindPower[]; powerLossList: PowerLoss[]; windPowerList: WindPowers[]; }> { //

    let startFomat: string = "";
    let endFomat: string = "";
    if (deviceIds == null)
      return Promise.reject("请选择风机！");
    if (dateType.toString() == '') return;

    startFomat = this.datePipe.transform(startTime, this.fomat);
    endFomat = this.datePipe.transform(endTime, this.fomat);
    //this.urlDate;
    return this.http.post(this.urlDate, JSON.stringify({ 'deviceIds': deviceIds, 'dateType': dateType, 'startTime': startFomat, 'endTime': endFomat }))
      .toPromise()
      .then(response => {
        let resault = response.json();
        try {
          switch (resault.code) {
            case "200":
              return resault.data;
            case "-1":
              throw new Error(resault.message);
          }
        }
        catch (error) {
          throw error;
        }
      })
      .catch(this.handleError);

  }

  /**
  * 获取风场年度电量损耗集合
  * 
  * @returns {Promise<ActualWindPower[]>} 
  * @memberof ActualWindPowerService
  */
  getYearPowerLossDataByFarmId(farmId: number, dateType: number, yearOrMonth: string): Promise<PowerLoss[]> {

    if (farmId.toString() == '')
      return Promise.reject("请选择风场！");
    if (dateType.toString() == '') return;

    return this.http.post(this.urlFarmYear, JSON.stringify({'farmId': farmId, 'dateType': dateType, 'yearOrMonth': yearOrMonth }))
      .toPromise()
      .then(response => {
        let resault = response.json();
        try {
          switch (resault.code) {
            case "200":
              return resault.data as PowerLoss[];
            case "-1":
              throw new Error(resault.message);
          }
        }
        catch (error) {
          throw error;
        }
      })
      .catch(this.handleError);

    // return Promise.resolve({'powerLossList': powerLossList as FarmLossPower[], 'turbPowerLoss': turbArr as PowerLoss[]})

  }

  //获取风场下风机年度损失电量
  getYearTurbinePowerLossDataByFarmId(farmId: number, dateType: number, yearOrMonth: string): Promise<PowerLoss[]> {
    if (farmId.toString() == '')
      return Promise.reject("请选择风场！");
    if (dateType.toString() == '') return;

    return this.http.post(this.urlTurbineYear, JSON.stringify({ 'farmId': farmId, 'dateType': dateType, 'yearOrMonth': yearOrMonth }))
      .toPromise()
      .then(response => {
        let resault = response.json();
        try {
          switch (resault.code) {
            case "200":
              return resault.data as PowerLoss[];
            case "-1":
              throw new Error(resault.message);
          }
        }
        catch (error) {
          throw error;
        }
      })
      .catch(this.handleError);
  }

  //获取风场月度损失电量
  getMonthPowerLossDataByFarmId(farmId: number, dateType: number, time: Date): Promise<PowerLoss[]> {

    let timeFomat: string = "";
    if (farmId.toString() == '')
      return Promise.reject("请选择风场！");
    if (dateType.toString() == '') return;

    timeFomat = this.datePipe.transform(time, this.fomat);
    //'http://192.168.15.150:8585/webapi/v1/powerLosses/getCurvePowGenAssVOListByOneYear'
    //this.urlFarmMonth

    return this.http.post(this.urlFarmMonth, JSON.stringify({ 'farmId': farmId, 'dateType': dateType, 'yearOrMonth': timeFomat }))
      .toPromise()
      .then(response => {
        let resault = response.json();
        try {
          switch (resault.code) {
            case "200":
              return resault.data as PowerLoss[];
            case "-1":
              throw new Error(resault.message);
          }
        }
        catch (error) {
          throw error;
        }
      })
      .catch(this.handleError);
  }

  //获取风场下风机月度损失电量
  getMonthTurbinePowerLossDataByFarmId(farmId: number, dateType: number, time: Date): Promise<PowerLoss[]> {

    let timeFomat: string = "";
    if (farmId.toString() == '')
      return Promise.reject("请选择风场！");
    if (dateType.toString() == '') return;

    timeFomat = this.datePipe.transform(time, this.fomat);

    return this.http.post(this.urlTurbineMonth, JSON.stringify({ 'farmId': farmId, 'dateType': dateType, 'yearOrMonth': timeFomat }))
      .toPromise()
      .then(response => {
        let resault = response.json();
        try {
          switch (resault.code) {
            case "200":
              return resault.data as PowerLoss[];
            case "-1":
              throw new Error(resault.message);
          }
        }
        catch (error) {
          throw error;
        }
      })
      .catch(this.handleError);
  }

  //风机发电能力评估（年度）
  getPowerLossDataByturbineId(deviceIds: number[], dateType: number, time: string): Promise<PowerLoss[]> {

    if (deviceIds == null)
      return Promise.reject("请选择风场！");
    if (dateType.toString() == '') return;
    //'http://192.168.15.150:8585/webapi/v1/powerLosses/getCurvePowGenAssVOListByOneYear'

    return this.http.post(this.urlTurbineIdYear, JSON.stringify({ 'deviceIds': deviceIds, 'dateType': dateType, 'yearOrMonth': time }))
      .toPromise()
      .then(response => {
        let resault = response.json();
        try {
          switch (resault.code) {
            case "200":
              return resault.data as PowerLoss[];
            case "-1":
              throw new Error(resault.message);
          }
        }
        catch (error) {
          throw error;
        }
      })
      .catch(this.handleError);
  }

  //风机发电能力评估（月度）
  getMonthPowerLossDataByturbineId(deviceIds: number[], dateType: number, time: Date): Promise<PowerLoss[]> {

    let timeFomat: string = "";
    if (deviceIds.toString() == '')
      return Promise.reject("请选择风机！");
    if (dateType.toString() == '') return;
    //'http://192.168.15.150:8585/webapi/v1/powerLosses/getCurvePowGenAssVOListByOneMonth'

    timeFomat = this.datePipe.transform(time, this.fomat);
    return this.http.post(this.urlTurbineIdMonth, JSON.stringify({ 'deviceIds': deviceIds, 'dateType': dateType, 'yearOrMonth': timeFomat }))
      .toPromise()
      .then(response => {
        let resault = response.json();
        try {
          switch (resault.code) {
            case "200":
              return resault.data as PowerLoss[];
            case "-1":
              throw new Error(resault.message);
          }
        }
        catch (error) {
          throw error;
        }
      })
      .catch(this.handleError);
  }

  private handleError(error: any): Promise<any> {
    return Promise.reject(error.message || error);
  }

}



// WEBPACK FOOTER //
// ./src/app/service/actual-wind-power.service.ts